package com.tz.crm.components;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.log4j.Logger;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.inject.Inject;
import java.sql.SQLException;

/**
 * DruidDataSource 数据源 实现类
 *
 * @author HuJingling
 * @since 2017/1/19
 */
@Component
public class MyDruidDataSource extends DruidDataSource {

    private static final Logger LOGGER = Logger.getLogger(MyDruidDataSource.class);

    /**
     * 构造函数
     *
     * @param env Environment
     */
    @Inject
    public MyDruidDataSource(Environment env) {
        LOGGER.debug("DruidDataSource init...");
        //基本属性
        String driver = env.getProperty("datasource.driver-class-name");
        String url = env.getProperty("datasource.url");
        String username = env.getProperty("datasource.username");
        String password = env.getProperty("datasource.password");
        LOGGER.trace("driver:" + driver);
        LOGGER.trace("url:" + url);
        LOGGER.trace("username:" + username);
        LOGGER.trace("password:" + password);
        setDriverClassName(driver);
        setUrl(url);
        setUsername(username);
        setPassword(password);
        //配置连接初始值、最小值
        setInitialSize(5);
        setMinIdle(5);
        //配置获取连接等待超时的 ms 时间
        setMaxWait(3 * 1000);
        //配置间隔多久 ms 时间进行一次检测，检测需要关闭的空闲连接
        setTimeBetweenEvictionRunsMillis(60 * 1000);
        //配置一个连接在池中最小生存 ms 时间
        setMinEvictableIdleTimeMillis(5 * 60 * 1000);
        //检测连接是否有效的 sql 语句
        setValidationQuery("select 1 from dual");
        setTestWhileIdle(true);
        setTestOnBorrow(false);
        setTestOnReturn(false);
        //配置监控统计拦截的filters
        try {
            setFilters("stat,log4j");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}
